package com.tsll.service.impl;

import com.tsll.dao.MenuMapper;
import com.tsll.entity.Menu;
import com.tsll.service.MenuService;
import com.tsll.vo.MenuTree;
import com.tsll.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

import java.util.List;


@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;




    public Result findByStaffId(Integer staffId) {
        //没有层级结构
        List<Menu> menus = menuMapper.selectAll(staffId);

        //1. 获取一级菜单
        List<Menu> first=new ArrayList<Menu>();
        for (Menu m:menus){
            //如果pid==0表示一级菜单
            if(m.getMenuParent()==0){
                first.add(m);
            }
        }
        childMenu(first,menus);
        return new Result(200,"查询左侧菜单成功",first);
    }

    public void childMenu(List<Menu> p, List<Menu> c){
        for (Menu m:p) {
            m.setChildren(new ArrayList<>());
            for (Menu n:c){
                if(m.getMenuId()==n.getMenuParent()){
                    m.getChildren().add(n);
                }
            }
            if(m.getChildren().size()>0) {
                childMenu(m.getChildren(), c);
            }

        }
    }


    public Result findByRoleId(Integer roleId) {
        //1.查询所有菜单--必须层级结构
        List<Menu> menus=menuMapper.selectAll02();
        //层级关系
        //1. 获取一级菜单
        List<Menu> first=new ArrayList<Menu>();
        for (Menu m:menus){
            //如果pid==0表示一级菜单
            if(m.getMenuParent()==0){
                first.add(m);
            }
        }
        childMenu(first,menus);



        //2.查询当前角色具有的菜单id.
        List<Integer> roleIds=menuMapper.selectMid(roleId);
        return new Result(200,"查询成功",new MenuTree(roleIds, first));
    }

    @Override
    @Transactional
    public Result confirmUpdate(Integer roleId, Integer[] menuIds) {
        //1.删除该角色具有的菜单
       int row1= menuMapper.deleteByRoleId(roleId);
        //2.添加--批量添加
        int row2= menuMapper.batchInsert(roleId, menuIds);

        if(row1==1){
            System.out.println("删除成功");
            if(row2>0){
                return new Result(200,"修改成功",null);
            }
        }
            return new Result(500,"修改失败",null);
    }
}
